<template>
    <div class="post">
        <!-- 帖子内容展示 -->
        <h2 @click="goToDetail(props.tieziData.id)">{{ props.tieziData.title }}</h2>
        <p>{{ props.tieziData.content }}</p>
        <p><strong>作者：</strong>{{ props.tieziData.user_name }} | <strong>发布时间：</strong>{{ props.tieziData.create_time }}</p>
        <p><strong>点赞数：</strong>{{ props.tieziData.like_num }}</p>

        <!-- 点赞按钮 -->
        <button @click="likePost(props.tieziData.id)">点赞</button>

        <!-- 回复按钮 -->
        <button @click="toggleReplies">{{ showReplies ? '收起' : '回复(' + props.tieziData.reply_num + ')' }}</button>

        <!-- 回复列表展示 -->
        <div v-if="showReplies" class="reply-container">
            <div v-if="login_status">
                <!-- 回复框 -->
                <el-form :model="replyForm" ref="form">
                    <el-form-item label="">
                        <el-input type="textarea" placeholder="请输入回复内容" v-model="replyForm.content"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="postReplys">发送回复</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <div v-for="reply in replys" :key="reply.id" class="reply">
                <p><strong>{{ reply.user_name }}</strong> 评论：</p>
                <p>{{ reply.content }}</p>
                <p><strong>点赞数：</strong>{{ reply.like_num }}</p>
                <p><strong>回复时间：</strong>{{ reply.reply_time }}</p>
                <button @click="likeReply(reply.id, reply)">点赞</button>
            </div>
        </div>
    </div>

    <!-- 固定的收起按钮 -->
    <div v-if="showReplies" class="toggle-button">
        <button @click="toggleReplies">收起评论区</button>
    </div>
</template>

<script setup>
import { GetTieziReplys, PostLike, PostTeiziReply } from '@/api/tiezi';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { defineProps } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const login_status = localStorage.getItem('login_status'); // 获取登录状态
const storedUser = JSON.parse(localStorage.getItem('user_info')); // 获取用户信息

// 跳转到帖子详情页
const goToDetail = (postId) => {
  router.push(`/tiezi/${postId}`);
};

// 使用 defineProps 定义子组件接收的属性
const props = defineProps({
    tieziData: {
        type: Object,
        required: true,
        default: () => ({})  // 设置默认值为空对象，防止 undefined 错误
    }
});

const replys = ref([]);
const replyPage = ref(1);
const showReplies = ref(false);

const replyForm = ref({
    post_id: props.tieziData.id, // 帖子ID
    content: '',
    user_id: storedUser.id, // 用户ID,
});

// 发送回复
const postReplys = async () => {
    try {
        const response = await PostTeiziReply(replyForm.value);
        const { code, msg, errors,reply_id } = response.data;

        if (code === 200) {
            ElMessage.success(msg); // 成功提示

            // 回复成功后，将新回复加入到回复列表中
            replys.value.push({
                user_name: storedUser.username,
                content: replyForm.value.content,
                like_num: 0, // 新回复的点赞数初始为0
                reply_time: new Date().toLocaleString(),
                id: reply_id, // 模拟一个id，这可以通过后端返回的实际id进行替换
            });

            // 清空回复框内容
            replyForm.value.content = '';
        } else if (code === 400) {
            if (errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);
                }
            } else {
                ElMessage.error(msg || '发送失败');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        // ElMessage.error('服务器错误，请稍后再试');
    }
};

// 点赞帖子
const likePost = async (post_id) => {
    props.tieziData.like_num++; // 本地更新点赞数
    const json = {
        user_id: storedUser.id,
        post_id: post_id,
    };
    try {
        const response = await PostLike(json);
        const { code, msg, errors } = response.data;

        if (code === 200) {
            ElMessage.success(msg);
        } else if (code === 400) {
            if (errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);
                }
            } else {
                ElMessage.error(msg || '点赞失败');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('服务器错误，请稍后再试');
    }
};

// 点赞回复
const likeReply = async (replyId, reply) => {
    reply.like_num++; // 本地更新点赞数
    const json = {
        user_id: storedUser.id,
        reply_id: replyId,
    };
    try {
        const response = await PostLike(json);
        const { code, msg, errors } = response.data;

        if (code === 200) {
            ElMessage.success(msg);
        } else if (code === 400) {
            if (errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);
                }
            } else {
                ElMessage.error(msg || '点赞失败');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('服务器错误，请稍后再试');
    }
};

// 切换回复列表的显示
const toggleReplies = async () => {
    showReplies.value = !showReplies.value;
    if (showReplies.value) {
        const res = await GetTieziReplys(props.tieziData.id, replyPage.value);
        replys.value = res.data.data;
    }
};

</script>

<style scoped>
/* 统一的外层容器，设置宽度最大值，并进行居中对齐 */
.post {
    max-width: 900px;
    width: 100%;
    margin: 20px auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}

.post:hover {
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

h2 {
    font-size: 1.8rem;
    color: #333;
    font-weight: bold;
    margin-bottom: 15px;
}

p {
    color: #555;
    font-size: 1rem;
    line-height: 1.6;
    margin-bottom: 10px;
}

strong {
    color: #333;
}

/* 调整按钮宽度以适应布局，确保按钮排列整齐 */
button {
    background-color: #409EFF;
    color: white;
    border: none;
    padding: 8px 18px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 1rem;
    margin-right: 12px;
    margin-bottom: 10px;
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #66b1ff;
}

button:disabled {
    background-color: #d3d3d3;
    cursor: not-allowed;
}

/* 评论区域的回复样式 */
.reply-container {
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    position: relative;
}

.reply p {
    margin: 6px 0;
    font-size: 1rem;
    color: #333;
}

/* 回复的点赞按钮样式 */
.reply button {
    background-color: #67C23A;
    padding: 6px 14px;
    font-size: 0.9rem;
    border-radius: 4px;
    margin-top: 8px;
}

.reply button:hover {
    background-color: #7ccf50;
}

.reply-time {
    color: #888;
    font-size: 0.9rem;
}

/* 回复框样式 */
.el-form-item {
    margin-bottom: 20px;
}

.el-input__inner {
    height: 120px;
    font-size: 1rem;
    border-radius: 8px;
    padding: 10px;
    border: 1px solid #dcdfe6;
    resize: none;
    box-sizing: border-box;
}

/* 回复按钮 */
.el-button {
    font-size: 1rem;
    padding: 10px 20px;
    background-color: #409EFF;
    color: white;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.el-button:hover {
    background-color: #66b1ff;
}

/* 固定按钮的样式 */
.toggle-button {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    display: block;
}

/* 在不同屏幕尺寸下的自适应调整 */
@media (max-width: 1200px) {
    .post {
        max-width: 800px;
    }
}

@media (max-width: 992px) {
    .post {
        max-width: 600px;
    }
    h2 {
        font-size: 1.7rem;
    }
}

@media (max-width: 768px) {
    .post {
        margin: 10px;
        padding: 15px;
        max-width: 100%;
    }
    h2 {
        font-size: 1.5rem;
    }
    p {
        font-size: 0.9rem;
    }
    button {
        padding: 8px 12px;
        font-size: 0.9rem;
        width: calc(50% - 10px);
        margin-right: 5px;
        margin-left: 5px;
    }
    .reply button {
        padding: 6px 12px;
        font-size: 0.85rem;
        width: auto;
    }
    .el-input__inner {
        height: 100px;
    }
    .toggle-button {
        width: 100%;
        padding: 0 15px;
        bottom: 10px;
    }
    .toggle-button button {
        width: 100%;
        max-width: 400px;
        margin: 0 auto;
        display: block;
    }
}

@media (max-width: 480px) {
    .post {
        margin: 5px;
        padding: 10px;
    }
    h2 {
        font-size: 1.3rem;
    }
    p {
        font-size: 0.85rem;
        line-height: 1.4;
    }
    button {
        width: 100%;
        margin: 5px 0;
    }
    .reply {
        padding: 10px 5px;
    }
}

/* 使输入框和按钮在竖屏设备上堆叠 */
.el-form {
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.el-form-item {
    width: 100%;
}

.el-input__inner, .el-button {
    width: 100%;
}
</style>
